#include <stdio.h>
#include <stdlib.h> //exit 函数头文件
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
  //execv 函数
  pid_t id = fork();
  if(id == 0)
  {
    printf("子进程创建成功 PID:%d   PPID:%d\n", getpid(), getppid());
    char* const argv[] = 
    {
      "ls",
      "-a",
      "-l",
      NULL
    };	//argv 表，实际为指针数组

    execv("/usr/bin/ls", argv);

    printf("程序替换失败\n");
    exit(255); //如果子进程有此退出码，说明替换失败
  }

  int status = 0;
  waitpid(id, &status, 0); //父进程阻塞等待
  if(WEXITSTATUS(status) != 255)
  {
    printf("子进程替换成功，程序正常运行 exit_code:%d\n", WEXITSTATUS(status));
  }
  else
  {
    printf("子进程替换失败，异常终止 exit_code:%d\n", WEXITSTATUS(status));
  }

  return 0;
}

